//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop


#include "Unit1.h"
#include "canlib.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
   int chanCount;
   Handle1 = canINVALID_HANDLE;
   canInitializeLibrary();
   if (canGetNumberOfChannels(&chanCount) < 0) Form1->Button1->Caption =    \
   "Fail to initialize";
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
   canBusOff(Handle1);
   int stat = canERR_PARAM;
   if((Handle1 = canOpenChannel(0, canWANT_EXCLUSIVE|canWANT_VIRTUAL)) < 0)
   if((Handle1 = canOpenChannel(1, canWANT_EXCLUSIVE|canWANT_VIRTUAL)) < 0)
   {
      Form1->Button1->Caption = "Fail to open channel";
      return; }
   stat = canSetBusParams(Handle1, BAUD_250K, 4, 4, 1, 1, 0);
   if (stat < 0)
   {
      Form1->Button1->Caption = "Fail to set bit rate";
      return; }
   canSetNotify(Handle1, Handle, canNOTIFY_TX|canNOTIFY_RX);
   canBusOn(Handle1);
   Form1->Button1->Caption = "Running...";
   Form1->Button1->Enabled = False;
}
//---------------------------------------------------------------------------



void __fastcall TForm1::WMCanLib(TWMCanLib& Message)
{
/*struct TWMCanLib
{
    Cardinal Msg;
    DWORD hnd;
    WORD event;
    WORD _pad;
    Longint Result;
};*/
   int stat;
   long id;
   unsigned int dlc, flags;
   unsigned char data[8];
   unsigned long time;
   char s[64];

   do
   {
      stat = canRead(Message.hnd, &id, data, &dlc, &flags, &time);
      if(Message.hnd == Handle1)
      {
         if (stat == canOK)
         {
            wsprintf(s, "Id: %d Dlc: %d  %s  %d ms",  id, dlc, data, time );
            Memo1->Lines->Add(s);
         }
      }



    } while (stat == canOK);
}


//---------------------------------------------------------------------------


